package com.atguigu.gmall.order.handler.impl;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.order.handler.AbstractOrderHandler;
import com.atguigu.gmall.order.dto.OrderSubmitDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Slf4j
public class RepeatValidOrderHandler extends AbstractOrderHandler {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public int sort() {
        return 1;
    }

    @Override
    public String process(OrderSubmitDto orderSubmitDto, String tradeNo) {

        // 使用lua脚本判断和删除交易号
        String script = "if redis.call('exists' , KEYS[1])\n" +
                "then\n" +
                "    return redis.call('del' , KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end" ;
        Long execute = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("order:info:tradeno:" + tradeNo));
        if(execute == 0) {      // 重复提交了
            throw new GmallException(ResultCodeEnum.ORDER_FORM_REPAT) ;
        }

        // 获取下一个步骤
        AbstractOrderHandler abstractOrderHandler = this.getNext();
        if(abstractOrderHandler != null) {
            return abstractOrderHandler.process(orderSubmitDto , tradeNo) ;
        }

        return null;
    }
}
